#include 	"commonheader.h"	

int
main(int argc, char **argv)
{
	int	sockfd, n;
	char	recvline[MAXLINE + 1];
	SAIN	servaddr;

	if (argc != 2){
		fprintf(stdout, "usage: %s <IPaddress>\n", argv[0]);
		exit(1);
	}


	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port   = htons(PORTA_SERVIDOR);	/* daytime server */
	if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) {
		fprintf(stdout,"inet_pton error for %s", argv[1]);
		exit(2);
	}

	if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0) {
		fprintf(stdout,"connect error");
                exit(-1);
        }

	struct sockaddr_storage ss;
	socklen_t 	len;

	len = sizeof(ss);
	if (getsockname (sockfd, (SA *) &ss, &len) < 0)	
		printf ("erro\n");
	if (ss.ss_family == AF_INET) {
		SAIN *s = (SAIN *) &ss;
		char buff[MAXLINE];
		int porta = ntohs(s->sin_port);
		inet_ntop(AF_INET,&s->sin_addr, buff, sizeof(buff));
	
		printf("IP local: %s Porta: %d\n", buff, porta);
	}

	while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
		recvline[n] = 0;	/* null terminate */
		if (fputs(recvline, stdout) == EOF)
			fprintf(stdout,"fputs error");
	}
	if (n < 0)
		fprintf(stdout,"read error");

	exit(0);
}
